<template>
  <div id="settingPage">
    <!-- 第一部分：顯示用戶基礎信息的卡片 -->
    <a-space direction="vertical" style="width: 100%">
      <a-card>
        <a-row :gutter="16">
          <a-col flex="none">
            <a-avatar
              :size="64"
              :style="{ backgroundColor: '#108ee9', verticalAlign: 'middle' }"
              :gap="1"
            >
              {{ authUserStore.userInfo.username.slice(0, 3) }}
            </a-avatar>
          </a-col>
          <a-col flex="auto">
            <p>用戶名: {{ userInfo.username }}</p>
            <p>電郵: {{ userInfo.email }}</p>
          </a-col>
        </a-row>
      </a-card>

      <!-- 第二部分：使用 Tab 切換基本信息設置和密碼重置設置 -->
      <a-card>
        <a-tabs default-active-key="1">
          <template #rightExtra
            ><a-switch
              v-model:checked="checked"
              checked-children="保護"
              un-checked-children="激活"
              @change="formDisabled = !checked"
          /></template>

          <a-tab-pane tab="基本信息" key="1">
            <!-- 設置表單佈局 -->
            <a-form
              :model="basicFormState"
              @submit.prevent="saveBasicInfo"
              :label-col="{ span: 6 }"
              :wrapper-col="{ span: 14 }"
              :disabled="formDisabled"
              ref="basicformRef"
            >
              <a-form-item label="用戶名">
                <a-input v-model:value="basicFormState.username" />
              </a-form-item>
              <a-form-item label="電郵">
                <a-input v-model:value="basicFormState.email" />
              </a-form-item>
              <a-form-item :wrapper-col="{ offset: 6, span: 14 }">
                <a-button
                  type="primary"
                  html-type="submit"
                  :loading="savingBasic"
                  >保存</a-button
                >
                <a-button style="margin-left: 8px" @click="resetBasicInfo"
                  >重置</a-button
                >
              </a-form-item>
            </a-form>
          </a-tab-pane>
          <a-tab-pane tab="密碼設置" key="2">
            <a-form
              :model="passwordFormState"
              @finish="handleChangePassword"
              :label-col="{ span: 6 }"
              :wrapper-col="{ span: 14 }"
              :disabled="formDisabled"
            >
              <input
                type="text"
                :value="authUserStore.userInfo.username"
                autocomplete="username"
                name="username"
                style="display: none"
                aria-hidden="true"
              />

              <a-form-item label="舊密碼">
                <a-input-password
                  v-model:value="passwordFormState.oldPassword"
                  autocomplete="current-password"
                />
              </a-form-item>
              <a-form-item
                label="新密碼"
                name="newPassword"
                :rules="[
                  { required: true, message: '請輸入新密碼' },
                  { min: 8, message: '密碼至少八位' },
                  {
                    pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/,
                    message: '需包含小寫字母和數字',
                  },
                ]"
              >
                <a-input-password
                  v-model:value="passwordFormState.newPassword"
                  autocomplete="new-password"
                  @blur="validatePasswordStrength"
                />
              </a-form-item>
              <a-form-item
                label="確認新密碼"
                name="confirmPassword"
                :rules="[
                  { required: true, message: '請確認新密碼' },
                  { validator: validatePasswordMatch },
                ]"
              >
                <a-input-password
                  v-model:value="passwordFormState.confirmPassword"
                  autocomplete="new-password"
                />
              </a-form-item>

              <a-form-item :wrapper-col="{ offset: 6, span: 14 }">
                <a-button
                  type="primary"
                  html-type="submit"
                  :loading="changingPassword"
                  >保存</a-button
                >
                <a-button style="margin-left: 8px" @click="resetPasswordForm"
                  >重置</a-button
                >
              </a-form-item>
            </a-form>
          </a-tab-pane>
        </a-tabs>
      </a-card>
    </a-space>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import { useAuthUserStore } from "@/store/authUserStore";
import { message } from "ant-design-vue";
import { authApi } from "@/api";

const authUserStore = useAuthUserStore();
const userInfo = authUserStore.userInfo;
// 表單狀態
const checked = ref<boolean>(false);
const formDisabled = ref(true);
const savingBasic = ref(false);
const changingPassword = ref(false);
// 基本信息設置相關數據
const basicFormState = reactive({
  username: userInfo.username,
  email: userInfo.email,
});

// 密碼重置設置相關數據
const passwordFormState = reactive({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});

// 保存基本信息的方法
const saveBasicInfo = async () => {
  try {
    await authApi.updateUserInfoRequest(basicFormState);
    message.success("基本信息更新成功");
    authUserStore.userInfo.username = basicFormState.username;
    authUserStore.userInfo.email = basicFormState.email;
  } catch (error) {
    console.error("更新失敗");
  } finally {
    checked.value = false;
    formDisabled.value = true;
    savingBasic.value = false;
  }
};
// 重置基本信息表單的方法
const resetBasicInfo = () => {
  basicFormState.username = userInfo.username;
  basicFormState.email = userInfo.email;
};

// 重置密碼的方法
const handleChangePassword = async () => {
  if (passwordFormState.newPassword !== passwordFormState.confirmPassword) {
    message.error("新密碼和確認密碼不一致");
    return;
  }
  // 這裡可以調用 API 進行密碼重置
  try {
    await authApi.changePasswordRequest(passwordFormState);
    message.success("密碼重置成功");
  } catch (error) {
    console.error("密碼重置失敗");
  } finally {
    resetPasswordForm();
    checked.value = false;
    formDisabled.value = true;
    changingPassword.value = false;
  }
};

// 重置密碼錶單的方法
const resetPasswordForm = () => {
  passwordFormState.oldPassword = "";
  passwordFormState.newPassword = "";
  passwordFormState.confirmPassword = "";
};

// 密碼強度實時驗證
const validatePasswordStrength = () => {
  const strongRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/;
  if (!strongRegex.test(passwordFormState.newPassword)) {
    message.warning("密碼需要包含大小寫字母和數字，至少八位");
  }
};

// 密碼一致性驗證
const validatePasswordMatch = (_rule: any, value: string) => {
  if (value !== passwordFormState.newPassword) {
    return Promise.reject("兩次輸入密碼不一致");
  }
  return Promise.resolve();
};
</script>

<style scoped>
/* 組件樣式 */
</style>
